<?php

namespace app\api\controller;

use app\common\model\Discuss as DiscussModel;
use app\common\service\Wechat;
use think\facade\Db;
use app\common\service\BaseService;

class Discuss extends ApiBase
{

    //话题列表
    public function list()
    {
        $keyword = input("keyword");
        $where = [];

        if ($keyword) {
            $where[] = ['title', "like", "%$keyword%"];
        }

        $list = DiscussModel::getList($where);
        return message($list);
    }

    //15天内按浏览量排序话题
    public function hot()
    {
        $list = DiscussModel::order("see_num desc")->whereTime('create_time', '-360 hours')->limit(6)->select();

        return message($list);
    }

    //添加话题
    public function addDis()
    {
        $userId = BaseService::getLoginUserId();
        $user = Db::name("user")->find($userId);

        if ($user["status"] != 0) {
            return error("该用户已被禁用");
        }

        $data = input("post.");
        $data["uid"] = $userId;
        $data["create_time"] = time();

        //微信小程序用户检测内容安全
        if ($user["type"] == 1) {
            $wechat = new Wechat();

            if ($data["title"] && !$wechat->checkText($data["title"], $user["openid"])) {
                return error("内容违规违法");
            }
        }

        $res = DiscussModel::create($data);
        if ($res) {
            return message("话题创建成功");
        }

        return error("话题创建失败");
    }

    public function detail()
    {
        $id = input("id");
        Db::name('discuss')->where('id', $id)->inc('see_num')->update();
        $res = DiscussModel::find($id);
        $res["post_count"] = DiscussModel::name("post")->where("discuss_id", $id)->count();
        return message($res);
    }

    public function infoByTitle()
    {
        $title = input("title");

        $info = DiscussModel::where('title', $title)->find();

        if (empty($info)) {
            $disData["id"] = BaseService::randomStr();
            $disData["user_id"] = BaseService::getLoginUserId();
            $disData["title"] = $title;

            $info = DiscussModel::create($disData);
        }

        Db::name('discuss')->where('id', $info->id)->inc('see_num')->update();

        return message($info);
    }

    //当前用户创建的话题
    public function myDis()
    {

        $uid = BaseService::getLoginUserId();
        $where["discuss.uid"] = $uid;
        $list = DiscussModel::getList($where);
        return message($list);
    }

    //删除话题
    public function del()
    {
        $id = input("id");
        $res = DiscussModel::destroy($id);
        if ($res) {
            return message("删除成功");
        }
        return error("删除失败");
    }

    //随机获取话题列表
    public function random()
    {
        $list = Db::name('discuss')->orderRaw('rand()')->limit(6)->select();
        return message($list);
    }
}